package com.leyou.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.vo.PageResult;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.dto.SpuDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.Spu;
import com.leyou.item.mapper.SpuDetailMapper;
import com.leyou.item.mapper.SpuMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SpuService {
    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private BrandService brandService;


    public PageResult<SpuDTO> querySpuByPage(String key, Integer page, Integer rows, Boolean saleable) {
        //分页
        PageHelper.startPage(page,rows);
        //查询关键字和上下架所有信息
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        if(StringUtils.isNotBlank(key)){
            criteria.andLike("name","%"+ key +"%");
        }
        if(saleable != null){
            criteria.andEqualTo("saleable",saleable);
        }
        example.setOrderByClause("update_time DESC");
        List<Spu> spuList = spuMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(spuList)){
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        //分装当前页信息
        PageInfo<Spu> spuPageInfo = new PageInfo<>(spuList);
        long total = spuPageInfo.getTotal();
        List<Spu> list = spuPageInfo.getList();

        List<SpuDTO> spuDTOList = BeanHelper.copyWithCollection(list, SpuDTO.class);
        //设置分类和品牌
        setCategoryAndBrand(spuDTOList);

        return new PageResult(total,spuDTOList);
    }

    private void setCategoryAndBrand(List<SpuDTO> spuDTOList) {
        for (SpuDTO spuDTO : spuDTOList) {
            //设置品牌
            Long brandId = spuDTO.getBrandId();
            BrandDTO brandDTO = brandService.queryBrandId(brandId);
            spuDTO.setBrandName(brandDTO.getName());


            //设置分类
            List<Long> categoryIds = spuDTO.getCategoryIds();
            //查询出分类
            List<CategoryDTO> categoryDTOS = categoryService.queryCategoryByIds(categoryIds);
            //通过
            String name = categoryDTOS.stream().map(CategoryDTO::getName).collect(Collectors.joining("/"));
            spuDTO.setCategoryName(name);
        }

    }
}
